import { defineComponent, computed, ref, watchEffect, createVNode } from 'vue';
import Checkbox from '../../inner/Checkbox.js';
import formFieldRef from '../../use/formFieldRef.js';

const index = /* @__PURE__ */ defineComponent({
  name: "CheckboxGroup",
  props: {
    block: {
      type: Boolean
    },
    name: {
      type: String
    },
    value: {
      type: Array
    },
    modelValue: {
      type: Array
    },
    disabled: {
      type: Boolean
    },
    data: {
      type: Array
    },
    textField: {
      type: String
    },
    valueField: {
      type: String
    },
    asFormField: {
      type: Boolean,
      default: true
    }
  },
  emits: ['change', 'update:modelValue'],
  setup(props, {
    emit
  }) {
    const classList = computed(() => ({
      'cm-checkbox-group': true,
      'cm-checkbox-group-stack': props.block
    }));
    const value = formFieldRef(props, emit, []);
    const _onChange = (checked, v) => {
      if (props.disabled) {
        return;
      }
      let val = value.value || [];
      if (checked) {
        if (!val.includes(v)) {
          val = val.concat(v);
        }
      } else {
        const index = val.indexOf(v);
        if (index > -1) {
          val.splice(index, 1);
        }
      }
      const newVal = JSON.parse(JSON.stringify(val));
      value.value = newVal;
      emit('change', newVal);
    };
    const textField = props.textField || 'label';
    const valueField = props.valueField || 'value';

    // 子元素的控制
    const controllers = {};
    if (props.data) {
      props.data.forEach(item => {
        const val = value.value || [];
        const checked = val.includes(item[valueField]);
        controllers[item[valueField]] = ref(checked);
      });
    }
    watchEffect(() => {
      const val = value.value ?? [];
      for (let i = 0; i < props.data.length; i++) {
        const item = props.data[i];
        const checked = val.includes(item[valueField]);
        controllers[item[valueField]].value = checked;
      }
    });
    return () => createVNode("div", {
      "class": classList.value
    }, [props.data.map(item => {
      return createVNode(Checkbox, {
        "disabled": props.disabled || item.disabled,
        "value": item[valueField],
        "checked": controllers[item[valueField]].value,
        "label": item[textField],
        "onChange": _onChange
      }, null);
    })]);
  }
});

export { index as default };
